package com.omesoft.hksnore.util.file;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.omesoft.hksnore.HMInfo;
import com.omesoft.hksnore.util.L;
import com.omesoft.hksnore.util.entity.HM;
import com.omesoft.hksnore.util.photo.SettingUtil;
import com.omesoft.hksnore.util.thread.MyThread;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by Omesoft on 2017/3/5.
 */

public class CreateFiles {
    static String filenameTemp = "";
    static ArrayList<Float> temp = new ArrayList<>();

    /**
     * 获取当前时间
     *
     * @param date
     * @return
     */
    public static String getTimeNameSql(Date date) {
        DecimalFormat df = new DecimalFormat("#000");
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmss");
        String timeName = dateFormat.format(date) + df.format(new Random().nextInt(999));
        return timeName;
    }

    public static String getNowTime(Date date) {
        DecimalFormat df = new DecimalFormat("#000");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String timeName = dateFormat.format(date) + df.format(new Random().nextInt(999));
        return timeName;
    }

    /**
     * 获取系统当前时间
     *
     * @return
     */
    public static String getDateFormatToString() {
        Date date = new Date();
        String format = "yyyy-MM-dd HH:mm:ss:SSS";
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        String dateStr = dateFormat.format(date);
        return dateStr;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    // 遍历接收一个文件路径，然后把文件子目录中的所有文件遍历并输出来
    public static List<HM> getAllFiles(File root) {
        List<HM> dataList = new ArrayList<HM>();
        File files[] = root.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    getAllFiles(f);
                } else {
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(f);
                        String fileSize = FormetFileSize(fis.available());

                        HM h = new HM();
                        h.settFileName(f.getName());
                        h.settFileSize(fileSize);
                        h.settUpdateTime(getNowTime(new Date(f.lastModified())));
                        h.setLastModified(f.lastModified());
                        dataList.add(h);
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        }
        Collections.sort(dataList, new FileComparator());
        return dataList;
    }

    /**
     * 修改文件名称
     *
     * @param oldFileName
     * @param newFileName
     */
    public static void updateFileName(String oldFileName, String newFileName) {
        File oldFile = new File(SettingUtil.TEXT_DIR + "/" + oldFileName);
        File newfile = new File(SettingUtil.TEXT_DIR + "/" + newFileName + ".txt");
        boolean flg = oldFile.renameTo(newfile);
    }

    /**
     * Check the SD card if there
     *
     * @return
     */
    public static boolean checkSDCard() {
        try {
            final String status = Environment.getExternalStorageState();
            if (status.equals(Environment.MEDIA_MOUNTED)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (file.exists()) { // 判断文件是否存在
            // if (file.isFile()) { // 判断是否是文件
            file.delete(); // delete()方法 你应该知道 是删除的意思;
            Log.e("muk", "文件已删除1。。。。。");
        } else {
            Log.e("muk", "文件不存在。。。。。");
        }
    }

    public static void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null)
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) { // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
    }

    public static void createFileDirs() {
        File file = new File(SettingUtil.TEXT_DIR);
        if (!file.exists()) {
            try {
                // 按照指定的路径创建文件夹
                file.mkdirs();
                Log.e("lgc", "创建存储文件夹。。。。。。");
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        File file1 = new File(SettingUtil.TEXT_RECORD_DIR);
        if (!file1.exists()) {
            try {
                // 按照指定的路径创建文件夹
                file1.mkdirs();
                Log.e("lgc", "创建存储文件夹。。。。。。");
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    // 创建文件夹及文件
    public static String CreateText(String time) {


        filenameTemp = time + ".txt";
        String filename = SettingUtil.TEXT_DIR + "/" + filenameTemp;
        Log.e("lgc", "filenameTemp：：：" + filenameTemp);
        File dir = new File(filename);
        if (!dir.exists()) {
            try {
                Log.e("lgc", "在指定的文件夹中创建文件。。。。。" + dir);
                // 在指定的文件夹中创建文件
                dir.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return filenameTemp;

    }

    // 创建文件夹及文件
    public static String CreateTextSource() {

        String time = getTimeNameSql(new Date());
        filenameTemp = time + ".txt";
        String filename = SettingUtil.TEXT_DIR + "/Source/" + time + ".txt";
        Log.e("lgc", "filenameTemp：：：" + filenameTemp);
        File dir = new File(filename);
        if (!dir.exists()) {
            try {
                Log.e("lgc", "在指定的文件夹中创建文件。。。。。");
                // 在指定的文件夹中创建文件
                dir.createNewFile();
            } catch (Exception e) {
            }
        }
        return filenameTemp;

    }

    // 向已创建的文件中写入数据-原始音频值
    public static void printSource(short[] value, String filenameTemp) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        String datetime = "";
        try {
            fw = new FileWriter(SettingUtil.TEXT_DIR + "/" + filenameTemp, true);//
            // 创建FileWriter对象，用来写入字符流
            bw = new BufferedWriter(fw); // 将缓冲对文件的输出
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            datetime = tempDate.format(new Date()).toString();
            String myreadline = "::" + datetime + "::";
            Log.d("sherlock", "value[]" + String.valueOf(value));
            for (int i = 0; i < value.length; i++) {
                myreadline = myreadline + "," + String.valueOf(value[i]);
            }
            bw.write(myreadline + "\n"); // 写入文件
            bw.newLine();
            bw.flush(); // 刷新该流的缓冲
            bw.close();
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
            }
        }
    }

    // 向已创建的文件中写入数据
    public static void print(float value, String filenameTemp) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        String datetime = "";
        temp.add(value);
        String myreadline = "";
        try {

            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            fw = new FileWriter(SettingUtil.TEXT_DIR + "/" + filenameTemp, true);//
            // 创建FileWriter对象，用来写入字符流
            bw = new BufferedWriter(fw); // 将缓冲对文件的输出

           if (temp.size() >=5) {
               datetime = tempDate.format(new Date()).toString();
               if (temp.size()%5 == 0 ){
                   myreadline = datetime + "," + temp.get(temp.size() - 5) + "," + temp.get(temp.size() - 4) + "," + temp.get(temp.size() - 3) + "," + temp.get(temp.size()- 2) + "," + temp.get(temp.size() - 1);

               }else {
                   return;
               }
           }else {
               return;
           }
           L.e("myreadline",myreadline);
            bw.write(myreadline + "\n"); // 写入文件
            bw.newLine();
            bw.flush(); // 刷新该流的缓冲
            bw.close();
            fw.close();
        } catch (IOException e) {//5.9  51.67  43.3
            // TODO Auto-generated catch block
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
            }
        }
    }
    // 向已创建的文件中写入数据
    public static void print2(String str, String filenameTemp) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        String datetime = "";
        String myreadline = "";
        try {

            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

            fw = new FileWriter(SettingUtil.TEXT_DIR + "/" + filenameTemp, true);
            // 创建FileWriter对象，用来写入字符流
            bw = new BufferedWriter(fw); // 将缓冲对文件的输出

           myreadline = tempDate+" "+str;
            Log.e("myreadline",str);
            bw.write(myreadline + "\n"); // 写入文件
            bw.newLine();
            bw.flush(); // 刷新该流的缓冲
            bw.close();
            fw.close();
        } catch (IOException e) {//5.9  51.67  43.3
            // TODO Auto-generated catch block
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
            }
        }
    }

    // 向已创建的文件中写入数据
    public static void print(List<HMInfo> hMInfoList, String filenameTemp) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(SettingUtil.TEXT_DIR + "/" + filenameTemp, true);//
            // 创建FileWriter对象，用来写入字符流
            bw = new BufferedWriter(fw); // 将缓冲对文件的输出
            // String myreadline = datetime + "[]" + str;
            Log.e("lgc", "hMInfoList.size()....." + hMInfoList.size());
            for (int i = 0; i < hMInfoList.size(); i++) {
                String myreadline = hMInfoList.get(i).gettTime() + "," + hMInfoList.get(i).gettValue();
                bw.write(myreadline + "\n"); // 写入文件
                bw.newLine();
                bw.flush(); // 刷新该流的缓冲
            }
            Log.e("lgc", "完成.....");
            bw.close();
            fw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            try {
                bw.close();
                fw.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
            }
        }
    }

    // /**
    // * 复制单个文件 把临时存储的文件放到 存储文件的目录下
    // */
    // public static void copyFile(String oldFileName, String newFileName) {
    //
    // try {
    // int bytesum = 0;
    // int byteread = 0;
    // File oldfile = new File(SettingUtil.TEMP_TEXT_DIR + "/"
    // + oldFileName);
    // if (oldfile.exists()) { // 文件存在时
    // InputStream inStream = new FileInputStream(
    // SettingUtil.TEMP_TEXT_DIR + "/" + oldFileName); // 读入原文件
    // FileOutputStream fs = new FileOutputStream(SettingUtil.TEXT_DIR
    // + "/" + newFileName + ".txt");
    // byte[] buffer = new byte[1444];
    // int length;
    // Date d = new Date();
    // Long time1 = d.getTime();
    // Log.e("lgc", "正在复制文件.....");
    // while ((byteread = inStream.read(buffer)) != -1) {
    // bytesum += byteread; // 字节数 文件大小
    // fs.write(buffer, 0, byteread);
    // }
    // inStream.close();
    // Date d2 = new Date();
    // Long time2 = d2.getTime();
    // Log.e("lgc", "复制文件   完成....." + ((time2 - time1) / 1000));
    // }
    // // 删除临时存储的文件
    // oldfile.delete();
    // } catch (Exception e) {
    // System.out.println("复制单个文件操作出错");
    // e.printStackTrace();
    //
    // }
    //
    // }

    public static void readFileOnLine(Context context, final String fileName, final int count) {// 输入文件路径

        MyThread.startNewThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    FileInputStream fis = new FileInputStream(SettingUtil.TEXT_DIR + "/" + fileName);// 打开文件输入流
                    StringBuffer sBuffer = new StringBuffer();
                    DataInputStream dataIO = new DataInputStream(fis);// 读取文件数据流
                    String strLine = null;
                    int i = 0;
                    while ((strLine = dataIO.readLine()) != null && i < count) {// 通过readline按行读取
                        i++;
                        sBuffer.append(strLine + "\n");// strLine就是一行的内容
                    }
                    Log.e("mul", "总行数:::" + i);
                    dataIO.close();
                    fis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }
}
